// 路由相关
const Router = require('@koa/router')
const Static = require('koa-static')
const path = require('path')
const mount = require('koa-mount')

// 返回一个模板页面
const html = `<!DOCTYPE html>`+
`<html lang="en">`+
`    <head>`+
`        <meta charset="UTF-8">`+
`        <meta http-equiv="X-UA-Compatible" content="IE=edge">`+
`        <meta name="viewport" content="width=device-width, initial-scale=1.0">`+
`        <title>Document</title>`+
// `     <script src="/common.js"></script>`+
`        <script src="/public/common.js"></script>`+
`    </head>`+
`    <body>`+
`        \${body}`+
`    </body>`+
`</html>`

const renderPage = (content) => {
    if(typeof content!== "string"){
        return html.replace("${body}", JSON.stringify(content))
    }

    return html.replace("${body}", content)
}




function useRouter (app) {
    // 1、静态资源托管：最好不用相对路径，受启动命令行路径影响
    const publicPath = path.resolve(__dirname, "../public")
    console.log("publicPath:", publicPath)

    app.use(
        // 可选插件：mount 插件给静态资源添加虚拟路径
        mount('/public', Static(publicPath))
        // Static(path.resolve(__dirname, "../public"))
    )

    // 2、koa 路由：https://github.com/koajs/router/blob/HEAD/API.md
    const router = new Router()

    router.get("/", (ctx, next) => {
        ctx.body = renderPage(ctx.request)
    })

    // 2.1、ctx.params 获取动态路径参数
    router.get("/page/:id", (ctx, next) => {
        ctx.body = renderPage(ctx.params)
    })

    // 2.2、路由重定向：针对同步请求！【遗留问题】怎么理解？
    router.get("/redirect", (ctx, next) => {
        ctx.redirect('/')
    })

    // 2.3、注册路由
    app
        .use(router.routes())
        .use(router.allowedMethods())
}


// module.exports = useRouter
export default useRouter